<template>
  <div class="menu-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="菜单名称">
              <el-input v-model="searchForm.title" placeholder="请输入菜单名称" clearable />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="handleAdd">新增菜单</el-button>
        </div>
      </template>

      <el-table
        :data="menuData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        v-loading="loading"
      >
        <el-table-column prop="title" label="菜单名称" width="220" />
        <el-table-column prop="icon" label="图标" width="100">
          <template #default="scope">
            <el-icon v-if="scope.row.icon">
              <component :is="scope.row.icon" />
            </el-icon>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由地址" width="200" />
        <el-table-column prop="component" label="组件路径" width="200" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.type === 'M'" type="success">目录</el-tag>
            <el-tag v-else-if="scope.row.type === 'C'" type="primary">菜单</el-tag>
            <el-tag v-else-if="scope.row.type === 'F'" type="info">按钮</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="handleAdd(scope.row)">新增</el-button>
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 菜单表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增菜单' : '编辑菜单'"
      width="600px"
    >
      <el-form
        ref="menuFormRef"
        :model="menuForm"
        :rules="menuRules"
        label-width="100px"
      >
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="menuForm.parentId"
            :data="menuOptions"
            placeholder="请选择上级菜单"
            node-key="id"
            :props="{ value: 'id', label: 'title', children: 'children' }"
            check-strictly
            default-expand-all
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="menuForm.type">
            <el-radio label="M">目录</el-radio>
            <el-radio label="C">菜单</el-radio>
            <el-radio label="F">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="title">
          <el-input v-model="menuForm.title" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="图标" prop="icon" v-if="menuForm.type !== 'F'">
          <el-input v-model="menuForm.icon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="路由地址" prop="path" v-if="menuForm.type !== 'F'">
          <el-input v-model="menuForm.path" placeholder="请输入路由地址" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component" v-if="menuForm.type === 'C'">
          <el-input v-model="menuForm.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="权限标识" prop="permission" v-if="menuForm.type !== 'M'">
          <el-input v-model="menuForm.permission" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="sort">
          <el-input-number v-model="menuForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="menuForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { menuApi } from '@/api/system'

// 搜索表单
const searchForm = reactive({
  title: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const menuData = ref([])

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const menuFormRef = ref(null)
const menuForm = reactive({
  id: null,
  parentId: 0,
  title: '',
  icon: '',
  path: '',
  component: '',
  type: 'M',
  permission: '',
  sort: 0,
  status: 1
})

// 上级菜单选项
const menuOptions = ref([
  { id: 0, title: '顶级菜单', children: [] }
])

// 表单校验规则
const menuRules = {
  title: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择菜单类型', trigger: 'change' }
  ],
  path: [
    { required: true, message: '请输入路由地址', trigger: 'blur' }
  ],
  component: [
    { required: true, message: '请输入组件路径', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入显示顺序', trigger: 'blur' }
  ]
}

// 初始化
onMounted(() => {
  fetchMenuTree()
})

// 获取菜单树
const fetchMenuTree = async () => {
  loading.value = true
  try {
    const res = await menuApi.getTree()
    if (res.data) {
      menuData.value = res.data
      // 更新菜单选项
      menuOptions.value = [
        { id: 0, title: '顶级菜单', children: JSON.parse(JSON.stringify(res.data)) }
      ]
    }
  } catch (error) {
    console.error('获取菜单树失败', error)
    ElMessage.error('获取菜单树失败')
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  fetchMenuTree()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 新增菜单
const handleAdd = (row) => {
  dialogType.value = 'add'
  resetMenuForm()

  if (row && row.id) {
    menuForm.parentId = row.id
  } else {
    menuForm.parentId = 0
  }

  dialogVisible.value = true
}

// 编辑菜单
const handleEdit = (row) => {
  dialogType.value = 'edit'
  resetMenuForm()

  menuForm.id = row.id
  menuForm.parentId = row.parentId
  menuForm.title = row.title
  menuForm.icon = row.icon
  menuForm.path = row.path
  menuForm.component = row.component
  menuForm.type = row.type
  menuForm.permission = row.permission
  menuForm.sort = row.sort
  menuForm.status = row.status

  dialogVisible.value = true
}

// 删除菜单
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该菜单吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await menuApi.delete(row.id)
      ElMessage.success('删除成功')
      fetchMenuTree()
    } catch (error) {
      console.error('删除失败', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 修改状态
const handleStatusChange = async (row) => {
  try {
    await menuApi.updateStatus(row.id, row.status)
    ElMessage.success(`状态修改${row.status === 1 ? '启用' : '禁用'}成功`)
  } catch (error) {
    console.error('状态修改失败', error)
    ElMessage.error('状态修改失败')
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 重置菜单表单
const resetMenuForm = () => {
  menuForm.id = null
  menuForm.parentId = 0
  menuForm.title = ''
  menuForm.icon = ''
  menuForm.path = ''
  menuForm.component = ''
  menuForm.type = 'M'
  menuForm.permission = ''
  menuForm.sort = 0
  menuForm.status = 1
}

// 提交表单
const handleSubmit = async () => {
  if (!menuFormRef.value) return
  
  await menuFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await menuApi.add(menuForm)
          ElMessage.success('添加成功')
        } else {
          await menuApi.update(menuForm)
          ElMessage.success('修改成功')
        }
        dialogVisible.value = false
        fetchMenuTree()
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加失败' : '修改失败', error)
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '修改失败')
      }
    }
  })
}
</script>

<style scoped>
.menu-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.search-form {
  margin-right: 20px;
}
</style> 